package com.LachesismStorm.lachesism.core.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;

public class AESUtil {

    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    private static final String KEY = "biaoxiaozhu2023!";

    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @param key     加密密钥
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
        byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
        cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(KEY));
        byte[] result = cipher.doFinal(byteContent);
        return Base64.encodeBase64String(result);
    }

    /**
     * AES 解密操作
     *
     * @param content 待解密内容
     * @param key     解密密钥
     * @return 返回解密后的数据
     */
    public static String decrypt(String content, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(KEY));
        byte[] result = cipher.doFinal(Base64.decodeBase64(content));
        return new String(result, StandardCharsets.UTF_8);
    }

    /**
     * 生成加密秘钥
     */
    private static Key getSecretKey(final String key) {
        return new SecretKeySpec(key.getBytes(), KEY_ALGORITHM);
    }

    public static void main(String[] args) throws Exception {
        String content = "15056010284";
        String key = "biaoxiaozhu2023!";
        System.out.println("加密前：" + content);
        String encryptContent = AESUtil.encrypt(content, key);
        System.out.println("加密后：" + encryptContent);
        String decryptContent = AESUtil.decrypt(encryptContent, key);
        System.out.println("解密后：" + decryptContent);
    }
}
